<template>
  <div class="timecounterwrap" :style="{color: color, fontSize: fsize}">
    <span class="van-tag van-tag--round tagred" v-if="overtime && tagpos === 'left'" :style="mstyle">超时</span>
    {{showstr}}
    <span class="van-tag van-tag--round tagred" v-if="overtime && tagpos != 'left'" :style="mstyle">超时</span>
  </div>
</template>

<script>
export default {
  name: 'TimeCounter',
  props: {
    timer: {
      type: Number // 从这个时间点算起
    },
    color: {
      type: String,
      default: 'inherit'
    },
    fsize: {
      type: String,
      default: 'inherit'
    },
    tagpos: {
      type: String,
      default: 'left'
    }
  },
  data () {
    return {
      overtime: false,
      nowtime: '',
      showstr: ''
    }
  },
  computed: {
    mstyle () {
      var sty = {}
      if (this.tagpos === 'left') {
        sty = {
          marginRight: '.1rem'
        }
      } else {
        sty = {
          marginLeft: '.1rem'
        }
      }
      return sty
    }
  },
  mounted () {
    this.nowtime = Math.round(((new Date()).getTime()) / 1000)
  },
  watch: {
    nowtime () {
      var left = this.timer - this.nowtime
      if (left < 0) {
        this.overtime = true
        left = -left
      } else {
        this.overtime = false
      }
      this.showstr = this.cm.gettimestr2(left)

      setTimeout(() => {
        this.nowtime++
      }, 1000)
    }
  }
}
</script>

<style lang="stylus" scoped>
/* 样式见common.styl */
</style>
